<template>
  <el-dialog :title="title" :visible="visible" width="85%" append-to-body @close="closeDialog">
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="缺陷名称" prop="defectName">
          <el-input
            v-model="queryParams.defectName"
            placeholder="请输入缺陷名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="缺陷等级" prop="defectLevel">
          <el-select
            v-model="queryParams.defectLevel"
            placeholder="请选择缺陷等级"
            clearable
            style="width: 100%"
          >
            <el-option label="致命缺陷" value="1" />
            <el-option label="轻微缺陷" value="2" />
            <el-option label="严重缺陷" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="queryParams.remark"
            placeholder="请输入备注"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleBatchDelete"
          >删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table
        v-loading="loading"
        :data="recordList"
        @selection-change="handleSelectionChange"
        border
        size="mini"
        style="width: 100%"
      >
        <el-table-column type="selection" width="45" align="center" />
        <el-table-column label="序号" align="center" type="index" width="50" />
        <el-table-column label="缺陷名称" align="center" prop="defectName" width="120" :show-overflow-tooltip="true" />
        <el-table-column label="缺陷等级" align="center" prop="defectLevel" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.defectLevel === '1'">致命缺陷</span>
            <span v-else-if="scope.row.defectLevel === '2'">轻微缺陷</span>
            <span v-else-if="scope.row.defectLevel === '3'">严重缺陷</span>
            <span v-else>{{ scope.row.defectLevel }}</span>
          </template>
        </el-table-column>
        <el-table-column label="缺陷数量" align="center" prop="defectQuantityNum" width="80" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改缺陷记录对话框 -->
    <el-dialog :title="formTitle" :visible="formOpen" width="500px" append-to-body @close="() => this.formOpen = false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="缺陷名称" prop="defectName">
          <el-input v-model="form.defectName" placeholder="请输入缺陷名称" />
        </el-form-item>
        <el-form-item label="检测类型" prop="qcType">
          <el-select v-model="form.qcType" placeholder="请选择检测类型" disabled>
            <el-option label="来料检测" value="1" />
            <el-option label="过程检测" value="2" />
            <el-option label="出货检测" value="3" />
            <el-option label="退料检测" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="缺陷数量" prop="defectQuantityNum">
          <el-input-number v-model="form.defectQuantityNum" :min="0" :precision="0" controls-position="right" />
        </el-form-item>
        <el-form-item label="缺陷等级" prop="defectLevel">
          <el-select v-model="form.defectLevel" placeholder="请选择缺陷等级">
            <el-option label="致命缺陷" value="1" />
            <el-option label="轻微缺陷" value="2" />
            <el-option label="严重缺陷" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelForm">取 消</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { listQcDefectRecord, addQcDefectRecord, updateQcDefectRecord, delQcDefectRecord, delQcDefectRecordById } from "@/api/qc/RecordAction";

export default {
  name: "DefectRecordDialog",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ""
    },
    // 检测单ID
    qcId: {
      type: [String, Number],
      default: null
    },
    // 检测单类型: 1-来料检测，2-过程检测，3-出货检测
    qcType: {
      type: [String, Number],
      default: "1"
    },
    // 检测单行ID（可选）
    lineId: {
      type: [String, Number],
      default: null
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 缺陷记录表格数据
      recordList: [],
      // 弹出层标题
      formTitle: "",
      // 是否显示弹出层
      formOpen: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        defectName: null,
        defectLevel: null,
        remark: null,
        qcId: null,
        qcType: null,
        lineId: null
      },
      // 表单参数
      form: {
        qcId: null,
        qcType: null,
        lineId: null
      },
      // 表单校验
      rules: {
        defectName: [
          { required: true, message: "缺陷名称不能为空", trigger: "blur" }
        ],
        qcType: [
          { required: true, message: "检测类型不能为空", trigger: "change" }
        ],
        defectQuantityNum: [
          { required: true, message: "缺陷数量不能为空", trigger: "blur" }
        ],
        defectLevel: [
          { required: true, message: "缺陷等级不能为空", trigger: "change" }
        ]
      }
    };
  },
  watch: {
    qcId: {
      handler(val) {
        if (val) {
          // 同步更新查询参数和表单中的检测单ID
          this.queryParams.qcId = val;
          this.form.qcId = val;
        }
      },
      immediate: true
    },
    qcType: {
      handler(val) {
        if (val) {
          // 同步更新查询参数和表单中的检测单类型
          this.queryParams.qcType = val;
          this.form.qcType = String(val); // 确保转换为字符串类型
        }
      },
      immediate: true
    },
    lineId: {
      handler(val) {
        if (val) {
          // 同步更新查询参数和表单中的检测单行ID
          this.queryParams.lineId = val;
          this.form.lineId = val;
        }
      },
      immediate: true
    },
    visible(val) {
      if (val) {
        if (this.qcId) {
          // 确保每次打开对话框时都重新设置相关参数并查询
          this.queryParams.qcId = this.qcId;
          this.queryParams.qcType = this.qcType;
          this.queryParams.lineId = this.lineId;
          
          this.form.qcId = this.qcId;
          this.form.qcType = String(this.qcType); // 确保转换为字符串类型
          this.form.lineId = this.lineId;
          
          // 立即查询数据
          this.getList();
        } else {
          this.$modal.msgWarning("未传入检测单ID，缺陷记录可能显示不正确");
        }
      }
    }
  },
  created() {
    // 组件创建时确保已设置必要的参数
    if (this.qcId) {
      this.queryParams.qcId = this.qcId;
      this.queryParams.qcType = this.qcType;
      this.queryParams.lineId = this.lineId;
      
      this.form.qcId = this.qcId;
      this.form.qcType = String(this.qcType); // 确保转换为字符串类型
      this.form.lineId = this.lineId;
    }
  },
  methods: {
    /** 关闭对话框 */
    closeDialog() {
      this.$emit('update:visible', false);
    },
    /** 查询缺陷记录列表 */
    getList() {
      // 设置加载状态
      this.loading = true;
      
      // 确保查询时始终带上必要参数
      if (this.qcId) {
        this.queryParams.qcId = this.qcId;
        this.queryParams.qcType = this.qcType;
        this.queryParams.lineId = this.lineId;
      } 
        
      if (!this.queryParams.qcId) {
        this.$modal.msgWarning("检测单ID未设置，可能无法获取正确的缺陷记录");
        this.loading = false;
        return;
      }
      
      // 发送请求
      listQcDefectRecord(this.queryParams).then(response => {
        this.recordList = response.rows;
        this.total = response.total;
      }).catch(error => {
        console.error("获取缺陷记录失败:", error);
        this.$modal.msgError("缺陷记录加载失败");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // 搜索前确保必要参数已设置
      if (this.qcId) {
        this.queryParams.qcId = this.qcId;
        this.queryParams.qcType = this.qcType;
        this.queryParams.lineId = this.lineId;
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 重置后立即设置必要参数
      this.queryParams.qcId = this.qcId; 
      this.queryParams.qcType = this.qcType;
      this.queryParams.lineId = this.lineId;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.recordId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.resetForm("form");
      this.form = {
        qcId: this.qcId,
        qcType: String(this.qcType), // 确保转换为字符串类型
        lineId: this.lineId,
        defectQuantityNum: 1,
        defectLevel: "2" // 默认为轻微缺陷
      };
      this.formOpen = true;
      this.formTitle = "添加缺陷记录";
    },
    
    /** 取消表单 */
    cancelForm() {
      this.formOpen = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.resetForm("form");
      const recordId = row.recordId || this.ids[0];
      Object.assign(this.form, row);
      this.formOpen = true;
      this.formTitle = "修改缺陷记录";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保表单提交时设置必要参数
          if (this.qcId && !this.form.qcId) {
            this.form.qcId = this.qcId;
          }
          if (this.qcType && !this.form.qcType) {
            this.form.qcType = String(this.qcType); // 确保转换为字符串类型
          }
          if (this.lineId && !this.form.lineId) {
            this.form.lineId = this.lineId;
          }
            
          if (!this.form.qcId) {
            this.$modal.msgWarning("未设置检测单ID，可能导致数据关联错误");
            return;
          }
          
          if (this.form.recordId != null) {
            updateQcDefectRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.cancelForm();
              this.getList();
            }).catch(() => {
              this.$modal.msgError("修改失败");
            });
          } else {
            addQcDefectRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.cancelForm();
              this.getList();
            }).catch(() => {
              this.$modal.msgError("新增失败");
            });
          }
        }
      });
    },
    /** 删除单条记录按钮操作 */
    handleDelete(row) {
      if (!row || !row.recordId) {
        this.$modal.msgWarning("请选择要删除的数据");
        return;
      }
      
      this.$modal.confirm('确认删除该缺陷记录?').then(() => {
        // 使用单个ID删除
        return delQcDefectRecordById(row.recordId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch((err) => {
        console.error("删除失败:", err);
        this.$modal.msgError("删除失败");
      });
    },
    
    /** 批量删除按钮操作 */
    handleBatchDelete() {
      if (!this.ids || this.ids.length === 0) {
        this.$modal.msgWarning("请选择要删除的数据");
        return;
      }
      
      this.$modal.confirm('确认删除选中的' + this.ids.length + '条缺陷记录?').then(() => {
        // 批量删除
        return delQcDefectRecord(this.ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch((err) => {
        console.error("删除失败:", err);
        this.$modal.msgError("删除失败");
      });
    }
  }
};
</script> 